// 全新技能树系统 - 简化版本
class NewSkillTreeSystem {
    constructor() {
        this.skillPoints = 25; // 初始技能点用于测试
        this.experience = 3000;
        this.playerSkills = {}; // 已学习的技能
        
        // 技能定义
        this.skillDefinitions = {
            // 战斗技能树
            combat: {
                name: '战斗专精',
                icon: '⚔️',
                skills: {
                    damage: {
                        name: '伤害提升',
                        description: '增加所有武器伤害 +10%',
                        icon: '💪',
                        maxLevel: 5,
                        cost: 2,
                        effects: { damageBonus: 0.1 }
                    },
                    speed: {
                        name: '攻击速度',
                        description: '增加射击速度 +15%',
                        icon: '⚡',
                        maxLevel: 3,
                        cost: 3,
                        requires: ['damage'],
                        effects: { speedBonus: 0.15 }
                    },
                    critical: {
                        name: '暴击精通',
                        description: '增加暴击率 +5%',
                        icon: '💥',
                        maxLevel: 3,
                        cost: 4,
                        requires: ['speed'],
                        effects: { criticalChance: 0.05 }
                    }
                }
            },
            
            // 生存技能树
            survival: {
                name: '生存专家',
                icon: '🛡️',
                skills: {
                    health: {
                        name: '生命强化',
                        description: '增加最大生命值 +20',
                        icon: '❤️',
                        maxLevel: 5,
                        cost: 2,
                        effects: { healthBonus: 20 }
                    },
                    regen: {
                        name: '生命恢复',
                        description: '每秒恢复1点生命',
                        icon: '💚',
                        maxLevel: 3,
                        cost: 3,
                        requires: ['health'],
                        effects: { regenRate: 1 }
                    },
                    mobility: {
                        name: '移动速度',
                        description: '增加移动速度 +15%',
                        icon: '🏃',
                        maxLevel: 3,
                        cost: 3,
                        requires: ['health'],
                        effects: { moveSpeed: 0.15 }
                    }
                }
            },
            
            // 技术技能树
            tech: {
                name: '科技专家',
                icon: '🔬',
                skills: {
                    reload: {
                        name: '快速装弹',
                        description: '减少装弹时间 25%',
                        icon: '🔄',
                        maxLevel: 4,
                        cost: 2,
                        effects: { reloadSpeed: 0.25 }
                    },
                    ammo: {
                        name: '弹药容量',
                        description: '增加弹药容量 +50%',
                        icon: '📦',
                        maxLevel: 3,
                        cost: 3,
                        requires: ['reload'],
                        effects: { ammoBonus: 0.5 }
                    },
                    penetration: {
                        name: '穿透子弹',
                        description: '子弹可以穿透敌人',
                        icon: '🏹',
                        maxLevel: 1,
                        cost: 5,
                        requires: ['ammo'],
                        effects: { penetration: true }
                    }
                }
            }
        };
        
        this.loadProgress();
        console.log('新技能树系统初始化完成');
    }
    
    // 打开技能树
    openSkillTree() {
        console.log('🌳 打开新技能树系统');
        
        // 确保菜单存在
        const skillTreeMenu = document.getElementById('skillTreeMenu');
        if (!skillTreeMenu) {
            console.error('找不到技能树菜单元素');
            return;
        }
        
        // 创建技能树内容
        this.createSkillTreeUI();
        
        // 显示菜单
        skillTreeMenu.classList.remove('hidden');
        
        console.log(`✅ 技能树打开成功 - 技能点: ${this.skillPoints}`);
    }
    
    // 创建技能树UI
    createSkillTreeUI() {
        const skillTreeContainer = document.getElementById('skillTreeContainer');
        if (!skillTreeContainer) {
            console.error('找不到技能树容器');
            return;
        }
        
        // 更新统计显示
        this.updateStats();
        
        // 生成HTML
        let html = '<div class="new-skill-trees">';
        
        Object.entries(this.skillDefinitions).forEach(([treeKey, tree]) => {
            html += this.generateTreeHTML(treeKey, tree);
        });
        
        html += '</div>';
        
        // 设置HTML
        skillTreeContainer.innerHTML = html;
        
        // 绑定所有事件
        this.bindAllEvents();
        
        // 添加样式
        this.addStyles();
        
        console.log('✅ 技能树UI创建完成');
    }
    
    // 生成单个技能树的HTML
    generateTreeHTML(treeKey, tree) {
        let html = `
            <div class="skill-tree-section" data-tree="${treeKey}">
                <h3 class="tree-title">
                    <span class="tree-icon">${tree.icon}</span>
                    ${tree.name}
                </h3>
                <div class="skills-grid">
        `;
        
        Object.entries(tree.skills).forEach(([skillKey, skill]) => {
            html += this.generateSkillHTML(treeKey, skillKey, skill);
        });
        
        html += '</div></div>';
        return html;
    }
    
    // 生成单个技能的HTML
    generateSkillHTML(treeKey, skillKey, skill) {
        const currentLevel = this.getSkillLevel(treeKey, skillKey);
        const isMaxLevel = currentLevel >= skill.maxLevel;
        const canAfford = this.skillPoints >= skill.cost;
        const hasRequirements = this.checkRequirements(treeKey, skill.requires || []);
        const canLearn = !isMaxLevel && canAfford && hasRequirements;
        
        let statusClass = '';
        if (isMaxLevel) statusClass = 'max-level';
        else if (canLearn) statusClass = 'available';
        else statusClass = 'locked';
        
        return `
            <div class="skill-item ${statusClass}" data-tree="${treeKey}" data-skill="${skillKey}">
                <div class="skill-icon">${skill.icon}</div>
                <div class="skill-info">
                    <h4 class="skill-name">${skill.name}</h4>
                    <p class="skill-desc">${skill.description}</p>
                    <div class="skill-level">等级: ${currentLevel}/${skill.maxLevel}</div>
                    <div class="skill-cost">消耗: ${skill.cost} 技能点</div>
                </div>
                ${canLearn ? 
                    `<button class="learn-btn" data-tree="${treeKey}" data-skill="${skillKey}" type="button">
                        学习
                    </button>` : 
                    `<div class="skill-status">
                        ${isMaxLevel ? '已满级' : (!canAfford ? '技能点不足' : '前置未满足')}
                    </div>`
                }
            </div>
        `;
    }
    
    // 绑定所有事件
    bindAllEvents() {
        console.log('🔗 开始绑定技能树事件...');
        
        // 1. 绑定返回按钮
        const backButton = document.getElementById('skillTreeBack');
        if (backButton) {
            // 移除旧监听器
            backButton.replaceWith(backButton.cloneNode(true));
            const newBackButton = document.getElementById('skillTreeBack');
            
            newBackButton.addEventListener('click', (e) => {
                console.log('🔙 返回按钮被点击');
                e.preventDefault();
                if (window.game) {
                    window.game.hideAllMenus();
                    window.game.showMenu('startMenu');
                }
            });
            console.log('✅ 返回按钮绑定成功');
        }
        
        // 2. 绑定重置按钮
        const resetButton = document.getElementById('resetSkillsBtn');
        if (resetButton) {
            // 移除旧监听器
            resetButton.replaceWith(resetButton.cloneNode(true));
            const newResetButton = document.getElementById('resetSkillsBtn');
            
            newResetButton.addEventListener('click', (e) => {
                console.log('🔄 重置按钮被点击');
                e.preventDefault();
                this.resetAllSkills();
            });
            console.log('✅ 重置按钮绑定成功');
        }
        
        // 3. 绑定所有学习按钮
        const learnButtons = document.querySelectorAll('.learn-btn');
        console.log(`找到 ${learnButtons.length} 个学习按钮`);
        
        learnButtons.forEach((button, index) => {
            button.addEventListener('click', (e) => {
                console.log(`🎯 学习按钮${index + 1}被点击`);
                e.preventDefault();
                e.stopPropagation();
                
                const treeKey = button.getAttribute('data-tree');
                const skillKey = button.getAttribute('data-skill');
                
                console.log(`尝试学习技能: ${treeKey}.${skillKey}`);
                this.learnSkill(treeKey, skillKey);
            });
        });
        
        console.log('✅ 所有事件绑定完成');
    }
    
    // 学习技能
    learnSkill(treeKey, skillKey) {
        console.log(`🎓 开始学习技能: ${treeKey}.${skillKey}`);
        
        const tree = this.skillDefinitions[treeKey];
        const skill = tree?.skills[skillKey];
        
        if (!skill) {
            console.error('技能不存在:', treeKey, skillKey);
            return false;
        }
        
        const currentLevel = this.getSkillLevel(treeKey, skillKey);
        
        // 检查条件
        if (currentLevel >= skill.maxLevel) {
            this.showMessage('技能已达到最高等级', 'warning');
            return false;
        }
        
        if (this.skillPoints < skill.cost) {
            this.showMessage(`技能点不足，需要 ${skill.cost} 点`, 'error');
            return false;
        }
        
        if (!this.checkRequirements(treeKey, skill.requires || [])) {
            this.showMessage('不满足前置技能要求', 'error');
            return false;
        }
        
        // 学习技能
        this.skillPoints -= skill.cost;
        
        if (!this.playerSkills[treeKey]) {
            this.playerSkills[treeKey] = {};
        }
        this.playerSkills[treeKey][skillKey] = currentLevel + 1;
        
        console.log(`✅ 成功学习技能: ${skill.name} (等级 ${currentLevel + 1})`);
        console.log(`剩余技能点: ${this.skillPoints}`);
        
        // 保存进度
        this.saveProgress();
        
        // 应用技能效果
        this.applySkillEffects();
        
        // 显示成功消息
        this.showMessage(`学习成功: ${skill.name}`, 'success');
        
        // 重新创建UI
        this.createSkillTreeUI();
        
        return true;
    }
    
    // 检查前置技能
    checkRequirements(treeKey, requires) {
        if (!requires || requires.length === 0) return true;
        
        return requires.every(reqSkill => {
            return this.getSkillLevel(treeKey, reqSkill) > 0;
        });
    }
    
    // 获取技能等级
    getSkillLevel(treeKey, skillKey) {
        return this.playerSkills[treeKey]?.[skillKey] || 0;
    }
    
    // 重置所有技能
    resetAllSkills() {
        if (!confirm('确定要重置所有技能吗？这将返还所有技能点。')) {
            return;
        }
        
        // 计算返还的技能点
        let totalSpent = 0;
        Object.entries(this.playerSkills).forEach(([treeKey, skills]) => {
            Object.entries(skills).forEach(([skillKey, level]) => {
                const skill = this.skillDefinitions[treeKey]?.skills[skillKey];
                if (skill) {
                    totalSpent += skill.cost * level;
                }
            });
        });
        
        // 重置
        this.playerSkills = {};
        this.skillPoints += totalSpent;
        
        this.saveProgress();
        this.createSkillTreeUI();
        
        this.showMessage(`技能重置成功！返还了 ${totalSpent} 个技能点`, 'success');
    }
    
    // 应用技能效果（增强版）
    applySkillEffects() {
        if (!window.player) {
            console.log('⚠️ 玩家对象不存在，跳过技能效果应用');
            return;
        }
        
        let totalEffects = {
            damageBonus: 0,
            speedBonus: 0,
            healthBonus: 0,
            moveSpeed: 0,
            regenRate: 0,
            reloadSpeed: 0,
            ammoBonus: 0,
            criticalChance: 0,
            penetration: false
        };
        
        // 累计所有技能效果
        Object.entries(this.playerSkills).forEach(([treeKey, skills]) => {
            Object.entries(skills).forEach(([skillKey, level]) => {
                const skill = this.skillDefinitions[treeKey]?.skills[skillKey];
                if (skill && skill.effects) {
                    Object.entries(skill.effects).forEach(([effect, value]) => {
                        if (typeof value === 'number') {
                            totalEffects[effect] += value * level;
                        } else {
                            totalEffects[effect] = value;
                        }
                    });
                }
            });
        });
        
        console.log('🎯 技能效果计算完成:', totalEffects);
        
        // 应用到玩家
        try {
            // 初始化基础值（如果还没有的话）
            this.initializePlayerBaseStats();
            
            // 应用生命值效果
            const oldMaxHealth = window.player.maxHealth;
            window.player.maxHealth = Math.max(100, window.player.baseMaxHealth + totalEffects.healthBonus);
            
            // 按比例调整当前血量
            if (oldMaxHealth > 0 && window.player.health > 0) {
                const healthRatio = window.player.health / oldMaxHealth;
                const newHealth = Math.floor(window.player.maxHealth * healthRatio);
                window.player.health = Math.min(newHealth, window.player.maxHealth);
            } else {
                window.player.health = window.player.maxHealth;
            }
            
            // 应用移动速度效果
            window.player.speed = Math.max(50, window.player.baseSpeed * (1 + totalEffects.moveSpeed));
            
            // 保存技能效果到玩家对象（供其他系统使用）
            window.player.skillEffects = totalEffects;
            
            // 应用到当前武器
            this.applySkillsToWeapon(window.player.currentWeapon, totalEffects);
            
            // 应用到所有武器（确保所有武器都受益）
            if (window.player.weapons && Array.isArray(window.player.weapons)) {
                window.player.weapons.forEach(weapon => {
                    this.applySkillsToWeapon(weapon, totalEffects);
                });
            }
            
            // 应用到近战武器
            if (window.player.meleeWeapon) {
                this.applySkillsToMeleeWeapon(window.player.meleeWeapon, totalEffects);
            }
            
            if (window.player.meleeWeapons && Array.isArray(window.player.meleeWeapons)) {
                window.player.meleeWeapons.forEach(weapon => {
                    this.applySkillsToMeleeWeapon(weapon, totalEffects);
                });
            }
            
            // 更新UI
            this.updatePlayerUI();
            
            console.log('✅ 技能效果应用成功');
            console.log(`🩸 生命值: ${window.player.health}/${window.player.maxHealth}`);
            console.log(`🏃 移动速度: ${window.player.speed}`);
            
        } catch (error) {
            console.error('❌ 应用技能效果失败:', error);
        }
    }
    
    // 初始化玩家基础属性
    initializePlayerBaseStats() {
        if (!window.player.baseMaxHealth) {
            window.player.baseMaxHealth = 100; // 默认基础生命值
        }
        if (!window.player.baseSpeed) {
            window.player.baseSpeed = 200; // 默认基础移动速度
        }
        
        console.log('🔧 玩家基础属性初始化完成');
    }
    
    // 应用技能到远程武器
    applySkillsToWeapon(weapon, effects) {
        if (!weapon || !weapon.weaponStats) return;
        
        // 初始化武器基础值
        if (!weapon.baseDamage) {
            weapon.baseDamage = weapon.weaponStats.damage;
        }
        if (!weapon.baseFireRate) {
            weapon.baseFireRate = weapon.weaponStats.fireRate;
        }
        if (!weapon.baseMaxAmmo) {
            weapon.baseMaxAmmo = weapon.weaponStats.maxAmmo;
        }
        if (!weapon.baseReloadTime) {
            weapon.baseReloadTime = weapon.weaponStats.reloadTime;
        }
        
        // 应用技能效果
        weapon.weaponStats.damage = Math.floor(weapon.baseDamage * (1 + effects.damageBonus));
        weapon.weaponStats.fireRate = Math.max(50, Math.floor(weapon.baseFireRate * (1 - effects.speedBonus)));
        weapon.weaponStats.reloadTime = Math.max(500, Math.floor(weapon.baseReloadTime * (1 - effects.reloadSpeed)));
        
        if (effects.ammoBonus > 0) {
            weapon.weaponStats.maxAmmo = Math.floor(weapon.baseMaxAmmo * (1 + effects.ammoBonus));
            weapon.weaponStats.clipSize = Math.floor(weapon.weaponStats.clipSize * (1 + effects.ammoBonus * 0.5));
        }
        
        // 更新武器的damage和fireRate属性（向后兼容）
        weapon.damage = weapon.weaponStats.damage;
        weapon.fireRate = weapon.weaponStats.fireRate;
        weapon.reloadTime = weapon.weaponStats.reloadTime;
        
        console.log(`🔫 武器${weapon.weaponStats.name}技能效果应用: 伤害${weapon.baseDamage}→${weapon.weaponStats.damage}`);
    }
    
    // 应用技能到近战武器
    applySkillsToMeleeWeapon(weapon, effects) {
        if (!weapon || !weapon.stats) return;
        
        // 初始化近战武器基础值
        if (!weapon.baseDamage) {
            weapon.baseDamage = weapon.stats.damage;
        }
        if (!weapon.baseAttackSpeed) {
            weapon.baseAttackSpeed = weapon.stats.attackSpeed;
        }
        if (!weapon.baseRange) {
            weapon.baseRange = weapon.stats.range;
        }
        
        // 应用技能效果
        weapon.stats.damage = Math.floor(weapon.baseDamage * (1 + effects.damageBonus));
        weapon.stats.attackSpeed = Math.max(200, Math.floor(weapon.baseAttackSpeed * (1 - effects.speedBonus)));
        weapon.stats.range = Math.floor(weapon.baseRange * (1 + effects.speedBonus * 0.2)); // 攻速也影响攻击范围
        
        // 更新武器的damage和attackSpeed属性（向后兼容）
        weapon.damage = weapon.stats.damage;
        weapon.attackSpeed = weapon.stats.attackSpeed;
        weapon.range = weapon.stats.range;
        
        console.log(`⚔️ 近战武器${weapon.stats.name}技能效果应用: 伤害${weapon.baseDamage}→${weapon.stats.damage}`);
    }
    
    // 更新玩家UI
    updatePlayerUI() {
        try {
            // 更新血量UI
            if (typeof window.player.updateHealthUI === 'function') {
                window.player.updateHealthUI();
            }
            
            // 更新武器信息UI
            if (window.gameEngine && typeof window.gameEngine.updateWeaponUI === 'function') {
                window.gameEngine.updateWeaponUI();
            }
            
        } catch (error) {
            console.log('⚠️ 更新UI时出现错误:', error);
        }
    }
    
    // 更新统计显示
    updateStats() {
        const expDisplay = document.getElementById('experienceDisplay');
        const pointsDisplay = document.getElementById('skillPointsDisplay');
        
        if (expDisplay) expDisplay.textContent = this.experience;
        if (pointsDisplay) pointsDisplay.textContent = this.skillPoints;
    }
    
    // 显示消息
    showMessage(text, type = 'info') {
        const messageDiv = document.createElement('div');
        messageDiv.className = `skill-message ${type}`;
        messageDiv.textContent = text;
        messageDiv.style.cssText = `
            position: fixed;
            top: 20px;
            right: 20px;
            padding: 15px 20px;
            border-radius: 8px;
            color: white;
            font-weight: bold;
            z-index: 10000;
            background: ${type === 'success' ? '#4CAF50' : type === 'error' ? '#f44336' : '#2196F3'};
            box-shadow: 0 4px 12px rgba(0,0,0,0.3);
            animation: slideInRight 0.3s ease-out;
        `;
        
        document.body.appendChild(messageDiv);
        
        setTimeout(() => {
            messageDiv.style.animation = 'slideOutRight 0.3s ease-in';
            setTimeout(() => {
                if (messageDiv.parentNode) {
                    messageDiv.parentNode.removeChild(messageDiv);
                }
            }, 300);
        }, 2000);
    }
    
    // 添加样式
    addStyles() {
        if (document.getElementById('newSkillTreeStyles')) return;
        
        const styles = document.createElement('style');
        styles.id = 'newSkillTreeStyles';
        styles.textContent = `
            .new-skill-trees {
                display: flex;
                flex-direction: column;
                gap: 20px;
                max-height: 60vh;
                overflow-y: auto;
                padding: 10px;
            }
            
            .skill-tree-section {
                background: rgba(40, 40, 40, 0.9);
                border: 2px solid #555;
                border-radius: 10px;
                padding: 15px;
            }
            
            .tree-title {
                display: flex;
                align-items: center;
                gap: 10px;
                margin: 0 0 15px 0;
                color: #fff;
                font-size: 18px;
            }
            
            .tree-icon {
                font-size: 24px;
            }
            
            .skills-grid {
                display: grid;
                grid-template-columns: repeat(auto-fit, minmax(250px, 1fr));
                gap: 15px;
            }
            
            .skill-item {
                background: rgba(60, 60, 60, 0.8);
                border: 2px solid #666;
                border-radius: 8px;
                padding: 12px;
                position: relative;
                transition: all 0.3s ease;
            }
            
            .skill-item.available {
                border-color: #4CAF50;
                background: rgba(76, 175, 80, 0.1);
            }
            
            .skill-item.available:hover {
                transform: translateY(-2px);
                box-shadow: 0 5px 15px rgba(76, 175, 80, 0.3);
            }
            
            .skill-item.max-level {
                border-color: #FFD700;
                background: rgba(255, 215, 0, 0.1);
            }
            
            .skill-item.locked {
                opacity: 0.6;
            }
            
            .skill-icon {
                font-size: 32px;
                text-align: center;
                margin-bottom: 8px;
            }
            
            .skill-name {
                color: #fff;
                font-size: 14px;
                margin: 0 0 5px 0;
                text-align: center;
            }
            
            .skill-desc {
                color: #ccc;
                font-size: 11px;
                margin: 0 0 8px 0;
                line-height: 1.3;
                text-align: center;
            }
            
            .skill-level, .skill-cost {
                color: #aaa;
                font-size: 10px;
                text-align: center;
                margin: 2px 0;
            }
            
            .learn-btn {
                background: linear-gradient(135deg, #4CAF50, #45a049);
                color: white;
                border: none;
                padding: 8px 16px;
                border-radius: 5px;
                cursor: pointer;
                font-size: 12px;
                font-weight: bold;
                width: 100%;
                margin-top: 8px;
                transition: all 0.2s ease;
            }
            
            .learn-btn:hover {
                background: linear-gradient(135deg, #45a049, #4CAF50);
                transform: scale(1.05);
            }
            
            .learn-btn:active {
                transform: scale(0.95);
            }
            
            .skill-status {
                text-align: center;
                padding: 8px;
                color: #999;
                font-size: 11px;
                border-radius: 5px;
                background: rgba(100, 100, 100, 0.2);
                margin-top: 8px;
            }
            
            @keyframes slideInRight {
                from { transform: translateX(100%); opacity: 0; }
                to { transform: translateX(0); opacity: 1; }
            }
            
            @keyframes slideOutRight {
                from { transform: translateX(0); opacity: 1; }
                to { transform: translateX(100%); opacity: 0; }
            }
        `;
        
        document.head.appendChild(styles);
    }
    
    // 保存进度
    saveProgress() {
        const saveData = {
            skillPoints: this.skillPoints,
            experience: this.experience,
            playerSkills: this.playerSkills
        };
        
        localStorage.setItem('newSkillTreeData', JSON.stringify(saveData));
    }
    
    // 加载进度
    loadProgress() {
        try {
            const saved = localStorage.getItem('newSkillTreeData');
            if (saved) {
                const data = JSON.parse(saved);
                this.skillPoints = data.skillPoints || 25;
                this.experience = data.experience || 3000;
                this.playerSkills = data.playerSkills || {};
                
                // 加载后立即应用技能效果
                setTimeout(() => {
                    this.applySkillEffects();
                }, 50);
            }
        } catch (error) {
            console.error('加载技能树数据失败:', error);
        }
    }
    
    // 启动技能效果更新循环（用于生命恢复等持续效果）
    startSkillEffectLoop() {
        if (this.skillEffectTimer) {
            clearInterval(this.skillEffectTimer);
        }
        
        this.skillEffectTimer = setInterval(() => {
            this.updateContinuousSkillEffects();
        }, 2000); // 改为每2秒更新一次，降低频率
        
        console.log('🔄 技能效果更新循环已启动（2秒间隔）');
    }
    
    // 停止技能效果更新循环
    stopSkillEffectLoop() {
        if (this.skillEffectTimer) {
            clearInterval(this.skillEffectTimer);
            this.skillEffectTimer = null;
        }
    }
    
    // 更新持续技能效果（如生命恢复）
    updateContinuousSkillEffects() {
        // 检查游戏状态，只在正常游戏中恢复
        if (!window.player || !window.player.skillEffects || 
            !window.gameEngine || window.gameEngine.gameState !== 'playing') {
            return;
        }
        
        // 额外安全检查：确保玩家血量大于0且游戏没有结束
        if (window.player.health <= 0) {
            console.log('🛑 玩家已死亡，停止生命恢复');
            this.stopSkillEffectLoop();
            return;
        }
        
        // 检查关卡是否仍然活跃
        if (window.gameManager && window.gameManager.levelManager && 
            !window.gameManager.levelManager.isLevelActive) {
            return;
        }
        
        const effects = window.player.skillEffects;
        
        try {
            // 生命恢复效果（添加安全检查和限制）
            if (effects.regenRate > 0 && window.player.health < window.player.maxHealth) {
                
                // 检查是否在战斗状态（受到伤害后3秒内不恢复）
                const now = Date.now();
                if (window.player.lastDamageTime && (now - window.player.lastDamageTime) < 3000) {
                    return; // 战斗状态下不恢复
                }
                
                // 检查是否被僵尸包围（距离太近的僵尸数量）
                let nearbyZombies = 0;
                if (window.gameEngine.zombies && Array.isArray(window.gameEngine.zombies)) {
                    try {
                        nearbyZombies = window.gameEngine.zombies.filter(zombie => {
                            if (!zombie || typeof zombie.x !== 'number' || typeof zombie.y !== 'number') {
                                return false;
                            }
                            const distance = Math.sqrt(
                                Math.pow(zombie.x - window.player.x, 2) + 
                                Math.pow(zombie.y - window.player.y, 2)
                            );
                            return distance < 100; // 100像素范围内
                        }).length;
                    } catch (zombieError) {
                        console.log('⚠️ 计算僵尸距离时出错:', zombieError);
                        nearbyZombies = 0;
                    }
                }
                
                // 如果周围有3个以上僵尸，降低恢复速率
                let actualRegenRate = effects.regenRate;
                if (nearbyZombies >= 3) {
                    actualRegenRate = Math.max(1, Math.floor(effects.regenRate * 0.3)); // 降低到30%
                } else if (nearbyZombies >= 1) {
                    actualRegenRate = Math.max(1, Math.floor(effects.regenRate * 0.7)); // 降低到70%
                }
                
                const oldHealth = window.player.health;
                window.player.health = Math.min(window.player.maxHealth, window.player.health + actualRegenRate);
                
                if (window.player.health > oldHealth) {
                    // 显示恢复效果（减少频率）
                    if (window.gameEngine && typeof window.gameEngine.showFloatingText === 'function' && 
                        (!this.lastRegenShow || (now - this.lastRegenShow) > 2000)) {
                        window.gameEngine.showFloatingText(window.player.x, window.player.y - 30, 
                            `+${actualRegenRate}`, '#90EE90', 12);
                        this.lastRegenShow = now;
                    }
                    
                    // 减少控制台输出频率
                    if (!this.lastRegenLog || (now - this.lastRegenLog) > 5000) {
                        console.log(`💚 生命恢复: ${oldHealth} → ${window.player.health} (+${actualRegenRate})`);
                        this.lastRegenLog = now;
                    }
                }
            }
            
            // 减少UI更新频率（每3秒更新一次而不是每秒）
            const now = Date.now();
            if (!this.lastUIUpdate || (now - this.lastUIUpdate) > 3000) {
                this.updatePlayerUI();
                this.lastUIUpdate = now;
            }
            
        } catch (error) {
            console.log('⚠️ 持续技能效果更新出错:', error);
        }
    }
    
    // 添加经验值
    addExperience(amount) {
        this.experience += amount;
        const newPoints = Math.floor(this.experience / 100) - Math.floor((this.experience - amount) / 100);
        if (newPoints > 0) {
            this.skillPoints += newPoints;
            this.showMessage(`获得 ${newPoints} 个技能点！`, 'success');
        }
        this.saveProgress();
    }
    
    // 当玩家装备新武器时调用此方法
    onWeaponEquipped(weapon) {
        if (!weapon || !window.player) return;
        
        console.log('🔫 检测到武器装备，应用技能效果...');
        
        // 重新应用技能效果到新武器
        if (window.player.skillEffects) {
            if (weapon.weaponStats) {
                this.applySkillsToWeapon(weapon, window.player.skillEffects);
            } else if (weapon.stats) {
                this.applySkillsToMeleeWeapon(weapon, window.player.skillEffects);
            }
            
            console.log('✅ 新装备武器的技能效果应用完成');
        }
    }
    
    // 为全局访问提供的便捷方法
    static applySkillsToWeaponGlobal(weapon) {
        if (window.newSkillTree && typeof window.newSkillTree.onWeaponEquipped === 'function') {
            window.newSkillTree.onWeaponEquipped(weapon);
        } else if (window.newSkillTreeSystem && typeof window.newSkillTreeSystem.onWeaponEquipped === 'function') {
            window.newSkillTreeSystem.onWeaponEquipped(weapon);
        }
    }
}